package org.qq.service.impl;

import io.github.melin.sqlflow.parser.SqlFlowParser;
import org.qq.enums.DatabaseTypeEnum;
import org.qq.exception.SqlParseException;
import org.qq.service.LineageService;
import org.qq.service.metadata.MetadataServiceFactory;
import org.qq.util.SQLLineageMerger;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Service
public class LineageServiceImpl implements LineageService {

    private static final Logger logger = LoggerFactory.getLogger(LineageServiceImpl.class);

    private final SqlFlowParser SQL_PARSER = new SqlFlowParser();
    private final MetadataServiceFactory metadataServiceFactory;
    private List<String> supportedDatabases;

    public LineageServiceImpl(MetadataServiceFactory metadataServiceFactory) {
        this.metadataServiceFactory = metadataServiceFactory;
    }

    @PostConstruct
    public void init() {
        supportedDatabases = DatabaseTypeEnum.getAllSupportedDatabases();
        logger.info("Supported databases initialized: {}", supportedDatabases);
    }

    @Override
    public List<String> getSupportedDatabases() {
        logger.debug("Getting supported databases");
        return supportedDatabases;
    }

    @Override
    public String analyzeSqlLineage(String databaseType,String isCreateTable, String columnName,String sql) {
        logger.info("Analyzing SQL lineage for database type: {}\n,isCreateTable: {}\n,columnName: {}", databaseType,isCreateTable,columnName);
        try {
            List<String> lineageStrList=metadataServiceFactory.getLineageStrList(databaseType,isCreateTable, sql);

             // 处理分析结果
            String result = SQLLineageMerger.mergeSQLLineage(lineageStrList,columnName);
            logger.info("SQL lineage analysis completed successfully");
            return result;
        } catch (IllegalArgumentException e) {
            logger.error("Unsupported database type: {}", e.getMessage(), e);
            throw new SqlParseException("不支持的数据库类型: " + e.getMessage(), e);
        } catch (Exception e) {
            logger.info("SQL解析失败: {}\n, SQL: {}\n,columnName: {}", databaseType, sql,columnName);
            logger.error("SQL解析失败: {}", e.getMessage(), e);
            throw new SqlParseException("SQL解析失败: " + e.getMessage(), e);
        }
    }
}